﻿using DFGK_WMS.IRepository;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Repository;
using DFGK_WMS.WebAPI.Controllers.Result;
using EnumsNET;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.ComponentModel;
using System.Data;
using System.Reflection;
using System.Security.Claims;
using static NPOI.HSSF.Util.HSSFColor;

namespace DFGK_WMS.WebAPI.Controllers.物料管理
{
    /// <summary>
    /// 物料
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TMateriaController : ControllerBase
    {
        public TMateriaController(ITMaterialRepository materialRepisotory)
        {
            MaterialRepisotory = materialRepisotory;
        }

        public ITMaterialRepository MaterialRepisotory { get; }

        /// <summary>
        /// 添加物料
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddMaterial(TMaterial m)
        {
            bool IsOK = MaterialRepisotory.AddMaterial(m);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败！编码已存在！", "500"));
        }

        /// <summary>
        /// 物料列表显示
        /// </summary>
        /// <param name="mname"></param>
        /// <param name="materialcategoryid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMaterialList(int? materialCategoryId,string? materialcategoryName, string? mname, decimal? startPrice, decimal? endPrice, int pageIndex = 1, int pageSize = 10)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            int totalCount;

            //if(materialcategoryid == 0)
            //{
            //    return Ok(BaseResult.Result(null, "查询成功！", "200", 0));
            //}

            var list = MaterialRepisotory.GetMaterialList(materialCategoryId,materialcategoryName, mname, startPrice,endPrice, pageIndex, pageSize, out totalCount);

            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        /// <summary>
        /// 物料删除
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DelMaterial(int mid)
        {
            if (mid <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            bool IsOK = MaterialRepisotory.DelMaterial(mid);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "删除成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败！", "500"));
        }

        /// <summary>
        /// 物料修改
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdMaterial(TMaterial m)
        {
            if (m.Id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            bool IsOK = MaterialRepisotory.UpdMaterial(m);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "修改成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "修改失败！编码已存在！", "500"));
        }

        /// <summary>
        /// 根据Id获取对象
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMaterialById(int mid)
        {
            if (mid <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var mobj = MaterialRepisotory.GetMaterialById(mid);
            if (mobj != null)
            {
                return Ok(BaseResult.Result(mobj, "获取成功", "200"));
            }
            return Ok(BaseResult.Result(null, "获取失败！", "500"));
        }

        /// <summary>
        /// 根据物料分类Id生成一个物料号
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMaterialCode(int mid)
        {
            if (mid <= 0)
            {
                return Ok(BaseResult.Result("500", "Id有误！"));
            }
            string IsOK = MaterialRepisotory.GetMaterialCode(mid);
            if (!string.IsNullOrEmpty(IsOK))
            {
                return Ok(BaseResult.Result(IsOK, "获取成功！", "200"));
            }
            return Ok(BaseResult.Result(IsOK, "获取失败！", "500"));
        }
        MemoryStream ProcessExcelData()
        {
            //模块从表中读取的数据
            List<TMaterial> list = new List<TMaterial>();
            list = MaterialRepisotory.GetTMaterialExcel();
            // 已经读取出了正确的数据后
            //创建Excel对象把数据赋值到对象中
            IWorkbook workbook = new XSSFWorkbook(); // Excel对象
            ISheet sheet1 = workbook.CreateSheet("物料管理");  // 创建Excel中的表对象
                                                           //表头
            IRow row0 = sheet1.CreateRow(0);  // 在sheet1表格中创建第0行
            row0.CreateCell(0).SetCellValue("物料名称");// 在sheet1表格中第0行创建第0列，并且在给这个单元格赋值
            row0.CreateCell(1).SetCellValue("物料号");
            row0.CreateCell(2).SetCellValue("型号规格");
            row0.CreateCell(3).SetCellValue("物料类型");
            row0.CreateCell(4).SetCellValue("毛重");
            row0.CreateCell(5).SetCellValue("净重");
            row0.CreateCell(6).SetCellValue("体积");
            row0.CreateCell(7).SetCellValue("最小安全库存");
            row0.CreateCell(8).SetCellValue("最大安全库存");
            row0.CreateCell(9).SetCellValue("创建人");
            row0.CreateCell(10).SetCellValue("创建时间");
            var rowIndex = 1;
            foreach (var item in list)
            {
                IRow row = sheet1.CreateRow(rowIndex);
                row.CreateCell(0).SetCellValue(item.Name);
                row.CreateCell(1).SetCellValue(item.Code);
                row.CreateCell(2).SetCellValue(item.ModelSpec);
                row.CreateCell(3).SetCellValue(item.TypeName);
                row.CreateCell(4).SetCellValue(0);
                row.CreateCell(5).SetCellValue(0);
                row.CreateCell(6).SetCellValue(0);
                row.CreateCell(9).SetCellValue(item.CreateUserName);
                row.CreateCell(10).SetCellValue(item.CreateDate.ToString());
                rowIndex++;
            }
            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);

            return ms;
        }
        /// <summary>
        /// 导出物料管理
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public FileContentResult DownTmater()
        {
            MemoryStream ms = ProcessExcelData();
            byte[] fileBytes = ms.ToArray();
            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, "物料管理.xlsx"); //关键语句
        }

        /// <summary>
        /// 导入Excel
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UploadUserInfo(IFormFile file)
        {
            try
            {             
                // 检查文件是否为空
                if (file == null || file.Length == 0)
                {
                    return Ok(BaseResult.Result("400", "没有选择文件或文件为空"));
                }
                string message = "";
                var postFile = Request.Form.Files[0];
                string extName = Path.GetExtension(postFile.FileName);
                if (!new string[] { ".xls", ".xlsx" }.Contains(extName))
                {
                    return Ok(BaseResult.Result("400", "必须是Excel文件"));
                }
                string uname = HttpContext.User.FindFirstValue("UserName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                MemoryStream ms = new MemoryStream();
                postFile.CopyTo(ms);
                ms.Position = 0;
                IWorkbook wb = null;
                if (extName.ToLower().Equals(".xls")) // 97-2003版本
                {
                    wb = new HSSFWorkbook(ms);
                }
                else
                {
                    wb = new XSSFWorkbook(ms); // 2007以上版本
                }

                ISheet sheet = wb.GetSheetAt(0);

                //总行数（0开始）
                int totalRow = sheet.LastRowNum;
                // 总列数（1开始）
                int totalColumn = sheet.GetRow(0).LastCellNum;
                bool chongfu = false;
                bool dbchongfu = false;
                List<TMaterial> stuList = new();
                for (int i = 1; i <= totalRow; i++)
                {

                    IRow row = sheet.GetRow(i);
                    string? TypeName = row.GetCell(0)?.StringCellValue;
                    string? MaterialCategoryName = row.GetCell(1)?.StringCellValue;
                    string? MaterialCategoryCode = row.GetCell(2)?.StringCellValue;
                    string? Name = row.GetCell(3)?.StringCellValue;
                    string? Code = row.GetCell(4)?.StringCellValue;
                    string? ModelSpec = "";
                    if (row.GetCell(5)?.CellType == CellType.String)
                    {
                        ModelSpec = row.GetCell(5)?.StringCellValue;
                    }
                    else
                    {
                        ModelSpec = row.GetCell(5)?.NumericCellValue.ToString();
                    }
                    string? UnitName = row.GetCell(6)?.StringCellValue;
                    string? QualityStateName = row.GetCell(7)?.StringCellValue;                 
                    decimal? ReceivePrice = (decimal?)row.GetCell(8)?.NumericCellValue;
                    int? Qty = (int?)row.GetCell(9)?.NumericCellValue;
                   
                    
                    int? ReceivedQty = (int?)row.GetCell(10)?.NumericCellValue;
                    
                    //if (string.IsNullOrEmpty(Articlebarcode) || Articlebarcode == "0" || string.IsNullOrEmpty(Code) || Code == "0" || string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(Shortname) || string.IsNullOrEmpty(UnitName) || string.IsNullOrEmpty(ModelSpec))
                    //{
                    //    continue;
                    //}
                    ////查询当前文件是否有重复的六九码
                    //chongfu = stuList.Where(x => x.Articlebarcode == Articlebarcode).Any();
                    //if (chongfu)
                    //{
                    //    message += Articlebarcode + "重复";
                    //    continue;
                    //}
                    ////查询库数据库中是否有重复的六九码
                    //dbchongfu = MaterialRepisotory.GetAll().Where(x => x.Articlebarcode == Articlebarcode).Any();
                    //if (dbchongfu)
                    //{
                    //    message += Articlebarcode + "重复";
                    //    continue;
                    //}

                    var user = new TMaterial
                    {
                        Code = Code,
                        Name = Name,
                        ModelSpec = ModelSpec,
                        TypeName = TypeName,
                        MaterialCategoryName = MaterialCategoryName,
                        MaterialCategoryCode = MaterialCategoryCode,
                        QualityState= QualityStateName=="新品"?1:0,
                        ReceivePrice= ReceivePrice,
                        Qty=Qty,
                        ReceivedQty=ReceivedQty,
                        UnitName = UnitName,
                        CreateUserId = uid,
                        CreateUserName = uname,
                        CreateDate = DateTime.Now,
                    };
                    stuList.Add(user);
                }
                if (stuList.Count <= 0)
                {
                    //message = "文件信息为空或别写字段为空！";
                    return Ok(BaseResult.Result(false, "导入失败！" + message, "500"));
                }
                bool result = MaterialRepisotory.AddMaterialList(stuList);
                wb.Close();
                if (result)
                {
                    return Ok(BaseResult.Result(stuList, "导入成功！" + message, "200"));
                }
                return Ok(BaseResult.Result(stuList, "导入失败！", "500"));
            }
            catch (Exception)
            {
                throw;
            }
        }


        /// <summary>
        /// 一键同步器材数据
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult AddMaterialListForSqlite()
        {
            var MateialList = MaterialRepisotory.GetAllMaterialList();
            if(MateialList == null)
            {
                return Ok(BaseResult.Result(false, "器材数据为空", "500"));
            }
            var IsOk = MaterialRepisotory.AddMaterialListForSqlite(MateialList);
            if (IsOk)
            {
                return Ok(BaseResult.Result(false, "同步成功", "200"));
            }
            return Ok(BaseResult.Result(false, "同步失败", "500"));

        }


        /// <summary>
        /// 导入Excel文件
        /// </summary>
        /// <param name="excelFile"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UploaMaterial(IFormFile file)
        {
            try
            {
                // 检查文件是否为空
                if (file == null || file.Length == 0)
                {
                    return Ok(BaseResult.Result("400", "没有选择文件或文件为空"));
                }
                string message = "";
                var postFile = Request.Form.Files[0];
                string extName = Path.GetExtension(postFile.FileName);
                if (!new string[] { ".xls", ".xlsx" }.Contains(extName))
                {
                    return Ok(BaseResult.Result("400", "必须是Excel文件"));
                }
                string uname = HttpContext.User.FindFirstValue("UserName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                MemoryStream ms = new MemoryStream();
                postFile.CopyTo(ms);
                ms.Position = 0;
                IWorkbook wb = null;
                if (extName.ToLower().Equals(".xls")) // 97-2003版本
                {
                    wb = new HSSFWorkbook(ms);
                }

                else
                {
                    wb = new XSSFWorkbook(ms); // 2007以上版本
                }

                ISheet sheet = wb.GetSheetAt(0);

                //总行数（0开始）
                int totalRow = sheet.LastRowNum;
                // 总列数（1开始）
                int totalColumn = sheet.GetRow(0).LastCellNum;
                List<TMaterial> materials = new();
                for (int i = 1; i <= totalRow; i++)
                {

                    IRow row = sheet.GetRow(i);

                    string? MaterialCategoryName = row.GetCell(0)?.StringCellValue;
                    if(MaterialCategoryName == null)
                    {
                        continue;
                    }
                    string? MaterialCategoryCode = row.GetCell(1)?.StringCellValue;
                    string? Name = row.GetCell(2)?.StringCellValue;
                    string? Code = row.GetCell(3)?.StringCellValue;
                    string? ModelSpec;
                    var cell = row.GetCell(4);
                    if (cell != null)
                    {
                        if (cell.CellType == CellType.String)
                        {
                            ModelSpec = cell.StringCellValue;
                        }
                        else if (cell.CellType == CellType.Numeric)
                        {
                            ModelSpec = cell.NumericCellValue.ToString();
                        }
                        else
                        {
                            ModelSpec = null;
                        }
                    }
                    else
                    {
                        ModelSpec = null;
                    }
                    string? UnitName = row.GetCell(5)?.StringCellValue;
                    decimal? Price;
                    if (row.GetCell(6)?.CellType == CellType.Numeric)
                    {
                        double numericValue = row.GetCell(6).NumericCellValue;
                        Price = Math.Round((decimal)numericValue, 2, MidpointRounding.AwayFromZero);
                    }
                    else
                    {
                        Price = null; // 或者设置一个默认值
                    }
                    //string? MaterialTypeName = row.GetCell(7)?.StringCellValue;
                    //string dateString = row.GetCell(3)?.StringCellValue; // 假设第四列是日期时间数据
                    //if (!string.IsNullOrEmpty(dateString) && DateTime.TryParse(dateString, out DateTime dateTime))
                    //{
                    //    DateTime? CreateDate = dateTime;
                    //    // 进行后续操作
                    //}
                    var dictItemsList =  MaterialRepisotory.GetDictItems(UnitName);
                    var materialCategoryList = MaterialRepisotory.GetCategoryByCode(MaterialCategoryCode);
                   // var materialGroupList = MaterialRepisotory.GetMaterialGroupByName(MaterialTypeName);

                    var material = new TMaterial
                    {
                        Name = Name,
                        Code = Code,
                        ModelSpec = ModelSpec,
                        UnitId = dictItemsList != null ? dictItemsList.Id : 0,
                        UnitName = UnitName,
                        TypeId = 0,
                        MaterialCategoryId = materialCategoryList != null ? materialCategoryList.Id : 0,
                        MaterialCategoryCode = MaterialCategoryCode,
                        MaterialCategoryName = MaterialCategoryName,
                        //MaterialGroupId = materialGroupList != null ? materialGroupList.Id : 0,
                        //MaterialGroupCode = materialGroupList != null ? materialGroupList.Code : "",
                        ReceivePrice = Price,
                        Price = Price,
                        CreateDate = DateTime.Now,
                    };
                    materials.Add(material);
                }
                if (materials.Count <= 0)
                {
                    //message = "文件信息为空或别写字段为空！";
                    return Ok(BaseResult.Result(false, "导入失败！" + message, "500"));
                }

                var result = MaterialRepisotory.UpdMaterial(materials);
                wb.Close();

                if (result)
                {
                    return Ok(BaseResult.Result(true, "导入成功！" + message, "200"));
                }
                return Ok(BaseResult.Result(false, "导入失败！", "500"));
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
